﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Pipes;

namespace InterprocessCommunicationClient
{
    public partial class ClientForm : Form
    {
        //NamedPipeClientStream m_PipeClient;
        const string m_PipeName = "ThisIsATestPipe";
        System.IO.FileSystemWatcher m_Watcher;

        public ClientForm()
        {
            InitializeComponent();
        }

        // C# to convert a string to a byte array.
        public static byte[] StrToByteArray(string str)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            return encoding.GetBytes(str);
        }

        void SentMessageToServer(string message)
        {
            try
            {
                //String[] listOfPipes = System.IO.Directory.GetFiles(@"\\.\pipe\");
                if (!System.IO.File.Exists(@"\\.\pipe\" + m_PipeName))
                {
                    return;
                }

                //byte[] buffer = { 0x0A, 0x0B, 0x0C, 0x0A, 0x0B, 0x0C, 0x0A, 0x0B, 0x0C };
                byte[] buffer = StrToByteArray(message);

                using (NamedPipeClientStream pipeClient =
                        new NamedPipeClientStream(".", m_PipeName, PipeDirection.Out, PipeOptions.Asynchronous))
                {
                    DateTime start = DateTime.Now;
                    pipeClient.Connect(100);
                    TimeSpan span = DateTime.Now - start;
                    this.Text = "Client - Took " + span.TotalMilliseconds + "ms to connect";

                    pipeClient.Write(buffer, 0, buffer.Length);
                }
            }
            catch (Exception ex)
            {
                bool test = true;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox2.Text = textBox1.Text;
            textBox2.Width = textBox2.PreferredSize.Width;
            SentMessageToServer(textBox1.Text);
        }
    }
}
